﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using MiniCrawler.DataAccess.Repositories;
using MiniCrawler.Entity;
using MiniCrawler.Logging;

namespace MiniCrawler.Business.Collectors.ResourceCollectors
{
    public class WallpaperHdDownloader
    {
        private DateTime start;
        private bool isContinue = true;
        List<DownloadLink> downloadingLinks = new List<DownloadLink>();
        public void Run()
        {
            start = DateTime.Now;
            Loop();

        }
        private  void Loop()
        {
            if (DownloadLinkHelper.HasUncheckedLinks() && isContinue)
            {
                var catLink = DownloadLinkHelper.SelectFirstUncheckedLinks();
                DownloadFiles(catLink);
                Log.WriteElapseTime(start);
            }
        }
        private void DownloadFiles(DownloadLink downloadLink)
        {

            try
            {
                string s = "D:\\DownloadFiles\\";
                string folder = downloadLink.Path;
                folder = folder.Replace("-gt;", "\\");

                Directory.CreateDirectory(s + folder);
                string fileName = Path.GetFileName(downloadLink.Value);


                WebClient webClient = new WebClient();

                
                webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1");
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);


                 IWebProxy proxy = WebRequest.GetSystemWebProxy();
                proxy.Credentials = CredentialCache.DefaultCredentials;

                webClient.Proxy = proxy;

                Log.WriteLog("[DOWNLOADING][" + downloadLink.Value + "]");
                DownloadLinkHelper.UpdateState(downloadLink, 2);
                
                //downloadingLinks.Add(downloadLink);

                var t = webClient.DownloadData(new Uri(downloadLink.Value));

                var z = webClient.DownloadString(new Uri(downloadLink.Value));
                var m = t.Count();

                webClient.DownloadFileAsync(new Uri(downloadLink.Value), @s + folder + "/" + fileName);
                isContinue = false;
            }
            catch (Exception ex)
            {
                LogService.Service.Error("FAILED TO DOWNLOAD FILES");
                LogService.Service.Error("Folder : " + downloadLink.Path);
                LogService.Service.Error("File : " + downloadLink.Value);
                throw;
            }

        }
        public AsyncCompletedEventHandler DownloadFileCompleted(DownloadLink downloadLink)
        {
            Action<object, AsyncCompletedEventArgs> action = (sender, e) =>
                                                                 {
                downloadLink.IsDownloaded = true;
                if (e.Error != null)
                {
                    throw e.Error;
                }
                DownloadLinkHelper.UpdateLink(downloadLink);
                DownloadLinkHelper.UpdateState(downloadLink, 3);
                var c = downloadingLinks.Count;
                                                                     isContinue = true;
                                                                     Loop();
                Log.WriteLog("[DOWNLOAD COMPLETE][FILE : " + Path.GetFileName(downloadLink.Value));
            };
            return new AsyncCompletedEventHandler(action);
        }
        private DownloadProgressChangedEventHandler ProgressChanged(DownloadLink downloadLink)
        {
            Action<object, DownloadProgressChangedEventArgs> action = (sender, e) => 
                Log.WriteLog("[DOWNLOADING][" + e.ProgressPercentage + "][" + Path.GetFileName(downloadLink.Value) + "]");

            return new DownloadProgressChangedEventHandler(action);
        }

        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Log.WriteCurrent("[DOWNLOADING : " + e.ProgressPercentage);
        }

        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            Log.WriteLog("[DOWNLOAD COMPLETE]");
            isContinue = true;
            Loop();


        }
    }
}
